package org.zcl.client;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Component;
import org.zcl.inteceptor.ClientLoginInterceptor;
import org.zcl.model.UserInfo;
import org.zcl.service.UserInfoService; /**
 * .
 *
 * @author zhuchenglin
 * @since 2024/8/9 15:50
 */
@Component
public class UserInfoApiClient {

    private static final String USERNAME = "admin";
    private static final String PASSWORD = "123456";
    private static final String ADDRESS = "http://localhost:8080/services/userInfoService?wsdl";

    /**
     * 使用代理方法
     * @param userInfo
     */
    public void saveUserInfoWithProxy(UserInfo userInfo) {
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
        jaxWsProxyFactoryBean.setAddress(ADDRESS);
        jaxWsProxyFactoryBean.setServiceClass(UserInfoService.class);
        jaxWsProxyFactoryBean.getOutInterceptors().add(
                new ClientLoginInterceptor(USERNAME, PASSWORD)
        );
        UserInfoService userInfoService = (UserInfoService) jaxWsProxyFactoryBean.create();
        userInfoService.saveUserInfo(userInfo);
    }

    /**
     * 使用动态代理
     * @param id
     * @throws Exception
     */
    public void getUserInfoByIdWithDynamic(Long id) throws Exception {
        JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
        Client client = clientFactory.createClient(ADDRESS);
        client.getOutInterceptors().add(new ClientLoginInterceptor(USERNAME, PASSWORD));
        Object[] userInfos = client.invoke("getUserInfoById", id);
        String userInfo = userInfos[0].toString();
        System.out.println(userInfo);
    }
}
